package routes

import (
	"illuminant/controller"
	"illuminant/middleware"
	"illuminant/service"
	"illuminant/util"
	"log"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
)

func jwtRoutes(r *gin.RouterGroup) {
	authMiddleware := middleware.JwtMiddleware()

	// codes for test where middleware
	// whereMiddleware := middleware.NewHasuraWhereMiddleware("id", "id", []string{"illuminant_user", "illuminant_user_aggregate"})
	// jwtAuthRoutes := r.Use(authMiddleware.MiddlewareFunc(), whereMiddleware)

	jwtAuthRoutes := r.Use(authMiddleware.MiddlewareFunc())

	jwtAuthRoutes.GET("/current_user", func(c *gin.Context) {
		claims := jwt.ExtractClaims(c)
		user, err := service.GetUserByID(claims["id"].(string))
		if err != nil {
			util.Fail(c, util.FAIL, err.Error(), nil)
			return
		}

		if user == nil {
			util.Fail(c, util.FAIL, "用户不存在", nil)
			return
		}

		util.Success(c, "success", user)
	})

	// change password
	jwtAuthRoutes.POST("/account/changepasswd", controller.ChangePasswd)

	// file upload
	jwtAuthRoutes.POST("/file/upload/:type", controller.UploadFile)
	jwtAuthRoutes.POST("/file/delete/:fileId", controller.DeleteFile)
	jwtAuthRoutes.POST("/file/refresh/:fileId", controller.RefreshFileStatus)

	// file download
	jwtAuthRoutes.GET("/file/download/:fileId", controller.DownloadFile)

	// graphql reverseproxy
	jwtAuthRoutes.POST("/graphql", util.ReverseProxy())

	// JUST websocket sample
	jwtAuthRoutes.GET("/ws", func(c *gin.Context) {
		ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			log.Println("error get connection")
			log.Fatal(err)
		}
		defer ws.Close()
		//读取ws中的数据
		mt, message, err := ws.ReadMessage()
		if err != nil {
			log.Println("error read message")
			log.Fatal(err)
		}

		// 返回message
		message = []byte(string(message) + " => response")
		err = ws.WriteMessage(mt, message)
		if err != nil {
			log.Println("error write message: " + err.Error())
		}
	})

}
